package com.kun.portal.webframe.util;

import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.persistence.Query;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2018/5/24.
 */
public class PageImpl<T> implements Page<T> {

    public PageImpl(Query query,Pageable pageable){
           query.setFirstResult(pageable.getPageSize()*(pageable.getPageNumber()));
           query.setMaxResults(pageable.getPageSize()+1);
           this.pageable = pageable;
           this.result=query.getResultList();
            this.size = this.result.size();
            if(this.result.size()>pageable.getPageSize()){
               result.remove(result.size()-1);
           }

    }
    private Pageable pageable;
    private  List<T>  result;
    private int size;
    @Override
    public int getTotalPages() {
        if(this.size>pageable.getPageSize()){
            return pageable.getPageNumber()+2;
        }
        return pageable.getPageNumber()+1;
    }

    @Override
    public long getTotalElements() {
        if(size>pageable.getPageSize()){
            return (pageable.getPageNumber()+2)*pageable.getPageSize()-1;
        }else{
           return pageable.getPageSize()*(pageable.getPageNumber())+size;
        }

    }

    @Override
    public int getNumber() {
        return pageable.getPageNumber();
    }

    @Override
    public int getSize() {
        return pageable.getPageSize();
    }

    @Override
    public int getNumberOfElements() {
        return result.size();
    }

    @Override
    public List<T> getContent() {
        return result;
    }

    @Override
    public boolean hasContent() {
        return size>0;
    }

    @Override
    public Sort getSort() {
        return pageable.getSort();
    }

    @Override
    public boolean isFirst() {

        return pageable.getPageNumber()==0;
    }

    @Override
    public boolean isLast() {
        return size<=pageable.getPageSize();
    }

    @Override
    public boolean hasNext() {
        return size>pageable.getPageSize();
    }

    @Override
    public boolean hasPrevious() {
        return pageable.hasPrevious();

    }

    @Override
    public Pageable nextPageable() {
        return pageable.next();
    }

    @Override
    public Pageable previousPageable() {
        return pageable.previousOrFirst();
    }

    @Override
    public <S> Page<S> map(Converter<? super T, ? extends S> converter) {
        return null;
    }

    @Override
    public Iterator<T> iterator() {
        return result.iterator();
    }
}
